package com.admin.utils.log.aspect;

import com.admin.utils.ip.IpUtils;
import com.admin.utils.log.aop.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author kuaiting
 */

@Component
@Slf4j
@Aspect
public class LogAspect {


    private long startTime;

    //@Autowired
    //private ExecutorAsyncService executorAsyncService;

    private String date = null;




    /**
     * <p> 切点声明
     */
    @Pointcut("execution(* com.admin.controller.*.*(..))")
    public void pointcut() {

    }


    @Before(value = "pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes servletRequestAttributes
                = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        StringBuffer requestURL = request.getRequestURL();

        String ip = IpUtils.getIpAddr(request);
        // 获取请求参数
        String requestUrl = request.getRequestURL().toString();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log aopLog = method.getAnnotation(Log.class);
        // 用户代理（客户端）
        String userAgent = request.getHeader("User-Agent");
        // 方法路径


        String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";

        StringBuilder params = new StringBuilder("{");
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        if (argValues != null) {
            for (int i = 0; i < argValues.length; i++) {
                params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
            }
        }
        params.append("}");
        // 设置请求参数

    }


    @AfterReturning(pointcut = "pointcut()", returning = "returnedValue")
    public void doAfterReturning(Object returnedValue) {
        long time = System.currentTimeMillis() - this.startTime;

    }

    @AfterThrowing(pointcut = "pointcut()", throwing = "throwable")
    public void doAfterThrowing(Throwable throwable) {


    }


}
